<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购销单管理工具 - 移动版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }

        .container {
            max-width: 100%;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .content {
            padding: 20px;
        }

        .section {
            margin-bottom: 25px;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
        }

        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .section-title::before {
            content: '';
            width: 4px;
            height: 20px;
            background: #4ECDC4;
            margin-right: 10px;
            border-radius: 2px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #4ECDC4;
        }

        .btn {
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 10px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #4ECDC4, #44A08D);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .sync-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }

        .sync-code {
            font-size: 32px;
            font-weight: bold;
            letter-spacing: 5px;
            margin: 15px 0;
            padding: 15px;
            background: rgba(255,255,255,0.2);
            border-radius: 8px;
        }

        .qr-code {
            margin: 15px 0;
            text-align: center;
        }

        .item-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        .item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .item:last-child {
            border-bottom: none;
        }

        .item-info {
            flex: 1;
        }

        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .item-details {
            font-size: 14px;
            color: #666;
        }

        .item-amount {
            font-size: 18px;
            font-weight: bold;
            color: #4ECDC4;
        }

        .total-section {
            background: linear-gradient(45deg, #FF6B6B, #FF8E53);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .total-amount {
            font-size: 28px;
            font-weight: bold;
            margin: 10px 0;
        }

        @media (max-width: 480px) {
            .container {
                margin: 5px;
                border-radius: 10px;
            }
            
            .header {
                padding: 15px;
            }
            
            .content {
                padding: 15px;
            }
            
            .sync-code {
                font-size: 24px;
                letter-spacing: 3px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📋 购销单管理</h1>
            <p>移动端专用版本</p>
        </div>

        <div class="content">
            <!-- 公司信息 -->
            <div class="section">
                <div class="section-title">🏢 公司信息</div>
                <div class="form-group">
                    <label>销售方</label>
                    <input type="text" id="seller" placeholder="请输入销售方名称">
                </div>
                <div class="form-group">
                    <label>购买方</label>
                    <input type="text" id="buyer" placeholder="请输入购买方名称">
                </div>
                <div class="form-group">
                    <label>单据日期</label>
                    <input type="date" id="date">
                </div>
            </div>

            <!-- 商品信息 -->
            <div class="section">
                <div class="section-title">📦 商品信息</div>
                <div class="form-group">
                    <label>商品名称</label>
                    <input type="text" id="itemName" placeholder="请输入商品名称">
                </div>
                <div style="display: flex; gap: 10px;">
                    <div class="form-group" style="flex: 1;">
                        <label>数量</label>
                        <input type="number" id="quantity" placeholder="数量">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label>单价</label>
                        <input type="number" id="price" placeholder="单价" step="0.01">
                    </div>
                </div>
                <button class="btn btn-primary" onclick="addItem()">➕ 添加商品</button>
            </div>

            <!-- 商品列表 -->
            <div class="section">
                <div class="section-title">📋 商品列表</div>
                <div class="item-list" id="itemList">
                    <div style="text-align: center; padding: 30px; color: #999;">
                        暂无商品，请添加商品
                    </div>
                </div>
            </div>

            <!-- 总计 -->
            <div class="total-section">
                <div>总金额</div>
                <div class="total-amount" id="totalAmount">¥0.00</div>
            </div>

            <!-- 操作按钮 -->
            <div class="section">
                <button class="btn btn-success" onclick="generateSyncCode()">🔄 生成同步码</button>
                <button class="btn btn-secondary" onclick="inputSyncCode()">📥 输入同步码</button>
                <button class="btn btn-primary" onclick="printOrder()">🖨️ 打印订单</button>
            </div>

            <!-- 同步区域 -->
            <div class="sync-section" id="syncSection" style="display: none;">
                <h3>📱 数据同步</h3>
                <div class="sync-code" id="syncCodeDisplay"></div>
                <div class="qr-code" id="qrCode"></div>
                <p>将此6位数字码输入到其他设备即可同步数据</p>
                <button class="btn" style="background: rgba(255,255,255,0.2); margin-top: 15px;" onclick="copySyncCode()">📋 复制数字码</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
    <script>
        let items = [];
        let currentSyncCode = '';

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('date').value = new Date().toISOString().split('T')[0];
            loadData();
        });

        // 添加商品
        function addItem() {
            const name = document.getElementById('itemName').value;
            const quantity = parseFloat(document.getElementById('quantity').value) || 0;
            const price = parseFloat(document.getElementById('price').value) || 0;

            if (!name || quantity <= 0 || price <= 0) {
                alert('请填写完整的商品信息');
                return;
            }

            const item = {
                id: Date.now(),
                name: name,
                quantity: quantity,
                price: price,
                amount: quantity * price
            };

            items.push(item);
            
            // 清空输入框
            document.getElementById('itemName').value = '';
            document.getElementById('quantity').value = '';
            document.getElementById('price').value = '';

            updateItemList();
            saveData();
        }

        // 更新商品列表显示
        function updateItemList() {
            const listElement = document.getElementById('itemList');
            
            if (items.length === 0) {
                listElement.innerHTML = '<div style="text-align: center; padding: 30px; color: #999;">暂无商品，请添加商品</div>';
            } else {
                listElement.innerHTML = items.map(item => `
                    <div class="item">
                        <div class="item-info">
                            <div class="item-name">${item.name}</div>
                            <div class="item-details">${item.quantity} × ¥${item.price.toFixed(2)}</div>
                        </div>
                        <div class="item-amount">¥${item.amount.toFixed(2)}</div>
                    </div>
                `).join('');
            }

            updateTotal();
        }

        // 更新总计
        function updateTotal() {
            const total = items.reduce((sum, item) => sum + item.amount, 0);
            document.getElementById('totalAmount').textContent = `¥${total.toFixed(2)}`;
        }

        // 生成同步码
        function generateSyncCode() {
            const data = {
                seller: document.getElementById('seller').value,
                buyer: document.getElementById('buyer').value,
                date: document.getElementById('date').value,
                items: items,
                timestamp: Date.now()
            };

            // 生成6位随机数字码
            currentSyncCode = Math.floor(100000 + Math.random() * 900000).toString();
            
            // 存储到本地（24小时有效）
            const syncData = {
                code: currentSyncCode,
                data: data,
                expires: Date.now() + 24 * 60 * 60 * 1000
            };
            
            localStorage.setItem(`sync_${currentSyncCode}`, JSON.stringify(syncData));

            // 显示同步码
            document.getElementById('syncCodeDisplay').textContent = currentSyncCode;
            document.getElementById('syncSection').style.display = 'block';

            // 生成二维码
            const qrElement = document.getElementById('qrCode');
            qrElement.innerHTML = '';
            QRCode.toCanvas(qrElement, currentSyncCode, {
                width: 200,
                height: 200,
                margin: 2
            }, function(error) {
                if (error) {
                    qrElement.innerHTML = '<p style="color: rgba(255,255,255,0.8);">二维码生成失败，请使用数字码</p>';
                }
            });

            // 滚动到同步区域
            document.getElementById('syncSection').scrollIntoView({ behavior: 'smooth' });
        }

        // 输入同步码
        function inputSyncCode() {
            const code = prompt('请输入6位数字同步码：');
            if (!code || code.length !== 6 || !/^\d{6}$/.test(code)) {
                alert('请输入正确的6位数字码');
                return;
            }

            const syncData = localStorage.getItem(`sync_${code}`);
            if (!syncData) {
                alert('同步码不存在或已过期');
                return;
            }

            try {
                const data = JSON.parse(syncData);
                if (Date.now() > data.expires) {
                    alert('同步码已过期');
                    localStorage.removeItem(`sync_${code}`);
                    return;
                }

                // 恢复数据
                document.getElementById('seller').value = data.data.seller || '';
                document.getElementById('buyer').value = data.data.buyer || '';
                document.getElementById('date').value = data.data.date || '';
                items = data.data.items || [];
                
                updateItemList();
                saveData();
                alert('数据同步成功！');
            } catch (error) {
                alert('数据格式错误');
            }
        }

        // 复制同步码
        function copySyncCode() {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(currentSyncCode).then(() => {
                    alert('同步码已复制到剪贴板');
                });
            } else {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = currentSyncCode;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('同步码已复制到剪贴板');
            }
        }

        // 打印订单
        function printOrder() {
            if (items.length === 0) {
                alert('请先添加商品');
                return;
            }

            const printWindow = window.open('', '_blank');
            const total = items.reduce((sum, item) => sum + item.amount, 0);
            
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>购销单</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        .header { text-align: center; margin-bottom: 30px; }
                        .info { margin-bottom: 20px; }
                        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
                        th, td { border: 1px solid #000; padding: 8px; text-align: left; }
                        th { background-color: #f0f0f0; }
                        .total { text-align: right; font-weight: bold; font-size: 18px; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h1>购销单</h1>
                    </div>
                    <div class="info">
                        <p><strong>销售方：</strong>${document.getElementById('seller').value}</p>
                        <p><strong>购买方：</strong>${document.getElementById('buyer').value}</p>
                        <p><strong>日期：</strong>${document.getElementById('date').value}</p>
                    </div>
                    <table>
                        <thead>
                            <tr>
                                <th>商品名称</th>
                                <th>数量</th>
                                <th>单价</th>
                                <th>金额</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${items.map(item => `
                                <tr>
                                    <td>${item.name}</td>
                                    <td>${item.quantity}</td>
                                    <td>¥${item.price.toFixed(2)}</td>
                                    <td>¥${item.amount.toFixed(2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                    <div class="total">
                        总计：¥${total.toFixed(2)}
                    </div>
                </body>
                </html>
            `);
            
            printWindow.document.close();
            printWindow.print();
        }

        // 保存数据到本地
        function saveData() {
            const data = {
                seller: document.getElementById('seller').value,
                buyer: document.getElementById('buyer').value,
                date: document.getElementById('date').value,
                items: items
            };
            localStorage.setItem('purchaseOrderData', JSON.stringify(data));
        }

        // 从本地加载数据
        function loadData() {
            const data = localStorage.getItem('purchaseOrderData');
            if (data) {
                try {
                    const parsed = JSON.parse(data);
                    document.getElementById('seller').value = parsed.seller || '';
                    document.getElementById('buyer').value = parsed.buyer || '';
                    document.getElementById('date').value = parsed.date || new Date().toISOString().split('T')[0];
                    items = parsed.items || [];
                    updateItemList();
                } catch (error) {
                    console.error('数据加载失败:', error);
                }
            }
        }

        // 自动保存
        document.getElementById('seller').addEventListener('input', saveData);
        document.getElementById('buyer').addEventListener('input', saveData);
        document.getElementById('date').addEventListener('change', saveData);
    </script>
</body>
</html>